// 1.Buffer Static API
// alloc(size[, fill, encoding])：创建指定size的Buffer实例，若未设fill则默认填满0
const alloc = Buffer.alloc(10);
console.log(alloc);// <Buffer 00 00 00 00 00 00 00 00 00 00>

// from(buffer)：复制参数buffer数据并创建新的Buffer实例
const fromCopy = Buffer.from(alloc);
console.log(fromCopy);// <Buffer 00 00 00 00 00 00 00 00 00 00>

// from(string[, encoding])：创建被string初始化的Buffer实例
const fromStr = Buffer.from('from-string');
console.log(fromStr);// <Buffer 66 72 6f 6d 2d 73 74 72 69 6e 67>

// from(array)：创建被array初始化的Buffer实例，若array元素是非数字则默认转为0
const fromArr = Buffer.from([1, '2', 'array']);
console.log(fromArr);// <Buffer 01 02 00>

// from(arrayBuffer[, byteOffset, length])：创建与参数arrayBuffer共享内存的Buffer实例
const fromShare = Buffer.from(alloc);
console.log(fromShare);

// concat(bufferArray[, length])：合并bufferArray数组内的Buffer，返回长度为length的新缓冲区
const concat = Buffer.concat([Buffer.from('string',), Buffer.from('boolean')], 10);
console.log(concat.toString());// stringbool


// 2.Buffer Instance API
// write(string[, offset, length, encoding])：从offset开始写入字节为length编码为encoding的string到缓冲区，返回实际写入大小
const write = alloc.write('write-string-offset', 2, 2);
console.log(write);// 2
console.log(alloc);// <Buffer 00 00 77 72 00 00 00 00 00 00>

// toString([encoding, start, end])：从缓冲区读编码为encoding开始位置为start结束位置为end的字符串，encoding默认utf8
const toString = alloc.toString(undefined, 2, 3);
console.log(toString);// w

// toJSON()：Buffer转为JSON对象
const toJSON = alloc.toJSON();
console.log(toJSON);// { type: 'Buffer', data: [0, 0, 119, 114, 0, 0, 0, 0, 0, 0] }

// compare(buffer)：比较两缓冲区
const compare1 = Buffer.from('001');
const compare2 = Buffer.from('002');
console.log(compare1.compare(compare2));// -1

// copy(targetBuffer[, targetStart, sourceStart, sourceEnd])：从sourceStart到sourceEnd复制原缓冲区到targetStart开始的targetBuffer
const copy1 = Buffer.from('copy1');
const copy2 = Buffer.from('copy2');
copy1.copy(copy2, 4, 4);
console.log(copy1.toString());// copy1
console.log(copy2.toString());// copy1

// length：缓冲区长度
const length = Buffer.from('length').length;
console.log(length);// 6